<template>
  <div class="upload-box">
    <el-upload
      :id="uuid"
      :accept="fileType.join(',')"
      :action="uploadUrl"
      :before-upload="beforeUploadVideo"
      :class="['upload', drag ? 'no-border' : '']"
      :disabled="disabled"
      :drag="drag"
      :http-request="httpRequest"
      :multiple="false"
      :on-error="uploadError"
      :on-progress="uploadVideoProcess"
      :on-success="handleVideoSuccess"
      :show-file-list="false"
    >
      <template v-if="modelValue && !videoFlag">
        <!-- 小视频直接显示 -->
        <video v-if="videoFileSize < 10" :src="modelValue" class="upload-video" controls></video>
        <!-- 大视频显示占位符 -->
        <div v-else class="video-placeholder">
          <Icon class="video-icon" icon="ep:video-camera"/>
          <span class="video-size">{{ formatFileSize(videoFileSize) }}</span>
          <span class="video-name">{{ getFileName(modelValue) }}</span>
        </div>

        <!-- 恢复原来的覆盖层按钮结构 -->
        <div class="upload-handle" @click.stop>
          <div v-if="!disabled" class="handle-icon" @click="editVideo">
            <Icon icon="ep:edit"/>
            <span v-if="showBtnText">{{ t('action.edit') }}</span>
          </div>
          <div class="handle-icon" @click="videoPreview(modelValue)">
            <Icon icon="ep:zoom-in"/>
            <span v-if="showBtnText">{{ t('action.detail') }}</span>
          </div>
          <div v-if="showDelete && !disabled" class="handle-icon" @click="deleteVideo">
            <Icon icon="ep:delete"/>
            <span v-if="showBtnText">{{ t('action.del') }}</span>
          </div>
        </div>
      </template>
      <template v-else-if="videoFlag">
        <div class="upload-progress">
          <el-progress :percentage="videoUploadPercent" type="circle"/>
        </div>
      </template>
      <template v-else>
        <div class="upload-empty">
          <slot name="empty">
            <Icon icon="ep:plus"/>
            <!-- <span>请上传视频</span> -->
          </slot>
        </div>
      </template>
    </el-upload>
    <div class="el-upload__tip">
      <slot name="tip"></slot>
    </div>
  </div>

  <!-- 使用视频预览组件 -->
  <VideoPreview
    v-model="previewVisible"
    :video-url="currentVideoUrl"
  />
</template>

<script lang="ts" setup>
import type {UploadProps} from 'element-plus'
import {generateUUID} from '@/utils'
import {propTypes} from '@/utils/propTypes'
import {useUpload} from '@/components/UploadFile/src/useUpload'

defineOptions({name: 'UploadVideo'})

// 接受父组件参数
const props = defineProps({
  modelValue: propTypes.string.def(''),
  drag: propTypes.bool.def(true), // 是否支持拖拽上传
  disabled: propTypes.bool.def(false), // 是否禁用上传组件
  fileSize: propTypes.number.def(50), // 视频大小限制，默认50M
  fileType: {
    type: Array,
    default: () => ['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb']
  },
  height: propTypes.string.def('178px'), // 组件高度
  width: propTypes.string.def('450px'), // 组件宽度增加
  borderradius: propTypes.string.def('8px'), // 组件边框圆角
  showDelete: propTypes.bool.def(true), // 是否显示删除按钮
  showBtnText: propTypes.bool.def(true), // 是否显示按钮文字
  directory: propTypes.string.def('video') // 上传目录
})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 组件状态
const uuid = ref('id-' + generateUUID())
const videoFlag = ref(false)
const videoUploadPercent = ref(0)

const previewVisible = ref(false)
const currentVideoUrl = ref('')

const videoFileSize = ref(0)

const emit = defineEmits(['update:modelValue'])

// 使用上传工具
const {uploadUrl, httpRequest} = useUpload(props.directory)

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1) return '未知大小'
  return size.toFixed(1) + ' MB'
}

// 从URL获取文件名
const getFileName = (url: string) => {
  if (!url) return '未知文件'
  try {
    const fileName = url.split('/').pop() || '视频文件'
    // 解码URL编码的文件名
    return decodeURIComponent(fileName)
  } catch (e) {
    return '视频文件'
  }
}

// 视频预览
const videoPreview = (videoUrl: string) => {
  currentVideoUrl.value = videoUrl
  previewVisible.value = true
}

const deleteVideo = () => {
  emit('update:modelValue', '')
  videoFileSize.value = 0
}

const editVideo = () => {
  const dom = document.querySelector(`#${uuid.value} .el-upload__input`)
  dom && dom.dispatchEvent(new MouseEvent('click'))
}

// 检测已有视频的大小
watch(() => props.modelValue, async (newVal) => {
  if (newVal) {
    try {
      // 尝试获取文件大小
      const response = await fetch(newVal, {method: 'HEAD'})
      const contentLength = response.headers.get('content-length')
      if (contentLength) {
        videoFileSize.value = parseInt(contentLength) / (1024 * 1024)
        console.log('视频大小：', videoFileSize.value)
      }
    } catch (e) {
      console.warn('无法获取视频大小', e)
    }
  } else {
    videoFileSize.value = 0
  }
}, {immediate: true})

// 验证视频格式和大小
const beforeUploadVideo: UploadProps['beforeUpload'] = (rawFile) => {
  videoFileSize.value = rawFile.size / 1024 / 1024
  const videoSize = rawFile.size / 1024 / 1024 < props.fileSize
  if (!props.fileType.includes(rawFile.type))
    message.notifyWarning('上传视频不符合所需的格式！')
  if (!videoSize)
    message.notifyWarning(`上传视频大小不能超过 ${props.fileSize}M！`)
  return props.fileType.includes(rawFile.type) && videoSize
}

// 上传进度显示
const uploadVideoProcess: UploadProps['onProgress'] = (event) => {
  videoFlag.value = true
  videoUploadPercent.value = Math.floor(event.percent)
}

// 视频上传成功处理
const handleVideoSuccess: UploadProps['onSuccess'] = (res: any) => {
  videoFlag.value = false
  videoUploadPercent.value = 0

  // 根据返回的数据结构调整
  if (res.code === 200 || (res.data)) {
    message.success('视频上传成功')
    const url = typeof res.data === 'string' ? res.data : res.data?.url
    emit('update:modelValue', url)
  } else {
    message.notifyError('视频上传失败，请重新上传！')
  }
}

// 视频上传错误提示
const uploadError = () => {
  videoFlag.value = false
  videoUploadPercent.value = 0
  message.notifyError('视频上传失败，请您重新上传！')
}
</script>

<style lang="scss" scoped>
.is-error {
  .upload {
    :deep(.el-upload),
    :deep(.el-upload-dragger) {
      border: 1px dashed var(--el-color-danger) !important;

      &:hover {
        border-color: var(--el-color-primary) !important;
      }
    }
  }
}

:deep(.disabled) {
  .el-upload,
  .el-upload-dragger {
    cursor: not-allowed !important;
    background: var(--el-disabled-bg-color);
    border: 1px dashed var(--el-border-color-darker) !important;

    &:hover {
      border: 1px dashed var(--el-border-color-darker) !important;
    }
  }
}

.upload-box {
  .no-border {
    :deep(.el-upload) {
      border: none !important;
    }
  }

  :deep(.upload) {
    .el-upload {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: v-bind(width);
      height: v-bind(height);
      overflow: hidden;
      border: 1px dashed var(--el-border-color-darker);
      border-radius: v-bind(borderradius);
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);

        .upload-handle {
          opacity: 1;
        }
      }

      .el-upload-dragger {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        padding: 0;
        overflow: hidden;
        background-color: transparent;
        border: 1px dashed var(--el-border-color-darker);
        border-radius: v-bind(borderradius);

        &:hover {
          border: 1px dashed var(--el-color-primary);
        }
      }

      .el-upload-dragger.is-dragover {
        background-color: var(--el-color-primary-light-9);
        border: 2px dashed var(--el-color-primary) !important;
      }

      .upload-video {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .video-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: var(--el-fill-color-light);

        .video-icon {
          font-size: 36px;
          color: var(--el-text-color-secondary);
          margin-bottom: 8px;
        }

        .video-size {
          font-size: 14px;
          color: var(--el-text-color-secondary);
          margin-bottom: 4px;
        }

        .video-name {
          font-size: 12px;
          color: var(--el-text-color-secondary);
          max-width: 90%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .upload-empty {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        line-height: 30px;
        color: var(--el-color-info);
        height: 100%;
        width: 100%;

        .el-icon {
          font-size: 28px;
          color: var(--el-text-color-secondary);
        }
      }

      .upload-progress {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
      }

      .upload-handle {
        position: absolute;
        top: 0;
        right: 0;
        display: flex;
        width: 100%;
        height: 100%;
        cursor: pointer;
        background: rgb(0 0 0 / 60%);
        opacity: 0;
        box-sizing: border-box;
        transition: var(--el-transition-duration-fast);
        align-items: center;
        justify-content: center;

        .handle-icon {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 0 6%;
          color: aliceblue;

          .el-icon {
            margin-bottom: 40%;
            font-size: 130%;
            line-height: 130%;
          }

          span {
            font-size: 85%;
            line-height: 85%;
          }
        }
      }
    }
  }

  .el-upload__tip {
    line-height: 18px;
    text-align: center;
    margin-top: 8px;
  }
}
</style>
